package fr.esiag.isidis.pdsTeam.Observer;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.Map;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JTable;

import fr.esiag.isidis.pdsTeam.views.TrainView;

class ButtonEditor extends DefaultCellEditor {
  

protected JButton button;
  private String label;
  private boolean isPushed;
  private int row;
  private int column;
  Map<Integer, TrainView> map;
  public ButtonEditor(JCheckBox checkBox,Map<Integer, TrainView> map) {
    super(checkBox);
    this.map=map;
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
    	  try {
    		  fireEditingStopped();
		} catch (Exception e2) {
			// TODO: handle exception
		}
       
      }
    });
  }

  public Component getTableCellEditorComponent(JTable table, Object value,
      boolean isSelected, int row, int column) {
	  this.row=row;
	  this.column=column;
    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());
    } else {
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());
    }
    label = (value == null) ? "" : value.toString();
    button.setText(label);
    isPushed = true;
    return button;
  }

  public Object getCellEditorValue() {
    if (isPushed) {
    	if(column==5)
    	{
    		
    	}
    	if(column==6)
    	{
    		if(label.equals("Arreter"))
    		{
    			getAt(row).arreter();
    			label="Demarrer";
    		}
    		else
    		{
    			getAt(row).demarrer();
    			label="Arreter";
    		}	
    	}
       //System.out.println(label +":" +getAt(row).getRow(5)[0]);
    }
    isPushed = false;
    return new String(label);
  }

  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }

  protected void fireEditingStopped() {
    super.fireEditingStopped();
  }
  
  public void setMap(Map<Integer, TrainView> map) {
		this.map = map;
	}
  
  TrainView getAt(int pos){
	  int i=0;
	  Iterator it = map.entrySet().iterator();
	    while (it.hasNext()) {
	        Map.Entry pairs = (Map.Entry)it.next();
	        TrainView train=((TrainView)pairs.getValue());
				if(i==pos) return train;
				i++;
	    }
	    return null;
  }
}